<?php
declare (strict_types = 1);

namespace app\command;

use app\api\model\BaseConfig as BaseConfigModel;
use app\api\model\MemberTransaction as MemberTransactionModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use app\admin\model\Member as MemberModel;
use think\console\Output;
use think\facade\Db;
use Workerman\Worker;
use Workerman\Lib\Timer;
use think\facade\Queue;
use Workerman\Connection\TcpConnection;
use think\log;

class Business extends Command
{
    protected $timer_id;

    protected function configure()
    {
        // 指令配置
        $this->setName('business')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('business');
    }

    protected function execute(Input $input, Output $output)
    {
        Worker::$pidFile = app()->getRootPath().'MyCrontab.pid';

        $action = $input->getArgument('action');

        $mode = $input->getOption('mode');

        global $argv;

        $argv = [];

        array_unshift($argv, 'think', $action);
        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        // 证书最好是申请的证书
        $context = array(
            'ssl' => array(
                'local_cert'        => '/www/server/panel/vhost/cert/wap.xinhuoio.com/fullchain.pem', // 也可以是crt文件
                'local_pk'          => '/www/server/panel/vhost/cert/wap.xinhuoio.com/privkey.pem',
                'verify_peer'       => false,
                'allow_self_signed' => true, //如果是自签名证书需要开启此选项
            )
        );

        $worker = new Worker('http://0.0.0.0:18791', $context);

        $worker->transport = 'ssl';

        $worker->onWorkerStart = function($worker)
        {

            $this->timer_id =   Timer::add(1, function()use($worker)
            {

                $entrustData['buy'] = Db::name('member_entrust')->field('sum(num) as num,money,sum(already_num) as already_num')->where('entrust_state',1)->where('transaction_state',1)->group('money')->order('money desc')->limit(6)->select()->toArray();

                $entrustData['sell'] = Db::name('member_entrust')->field('sum(num) as num,money,sum(already_num) as already_num')->where('entrust_state',1)->where('transaction_state',2)->group('money')->order('money asc')->limit(6)->select()->toArray();

                $entrustData['adc_transaction'] = sprintf("%.4f",BaseConfigModel::config_data('adc_transaction'));

                usort($entrustData['sell'], function ($current, $next)
                {
                    return $current['money'] < $next['money'];
                });


                foreach ($entrustData['sell'] as $k=>$v)
                {
                    if($v['already_num'])   $entrustData['sell'][$k]['num'] = bcsub($v['num'],$v['already_num'],4);
                }

                foreach ($entrustData['buy'] as $k=>$v)
                {
                    if($v['already_num'])   $entrustData['buy'][$k]['num'] = bcsub($v['num'],$v['already_num'],4);
                }

                foreach ($worker->connections as $connection)
                {

                    $connection->send(json_encode($entrustData));

                }

            });

        };
        $worker->onMessage = function(TcpConnection $connection, $data)
        {
            if($data)
            {
                $member = MemberModel::address($data);

                Timer::add(1, function () use ($connection, $member) {
                    if ($member) {

                        $data = Db::name('member_entrust')->where(['mid' => $member->id, 'entrust_state' => 1])->order('create_time desc')->select();

                    } else {
                        $data = [];
                    }
                    $connection->send(json_encode($data));
                });
            }
        };
        // 运行worker
        Worker::runAll();
    }

}
